/* eslint-disable react/prop-types */
import React, { useRef, useEffect } from 'react';
import { useDebounceFn } from 'ahooks';
import * as echarts from 'echarts';
import emitter from '#/utils/events';

function Charts({ config = {} }) {
  let chartInstance = null;
  const chartRef = useRef(null);

  const resizeHelper = useDebounceFn(
    () => {
      chartInstance =
        echarts.getInstanceByDom(chartRef?.current) || echarts.init(chartRef?.current);
      chartInstance?.resize();
    },
    { wait: 300 },
  );

  useEffect(() => {
    mounted();
    return () => {
      destoryed();
    };
  }, []);

  useEffect(() => {
    renderChart();
  }, [JSON.stringify(config)]);

  function destoryed() {
    chartInstance?.dispose();
    window.removeEventListener('resize', resizeHelper.run);
    emitter.removeListener('onChangeMnue', resizeHelper.run);
  }

  function mounted() {
    window.addEventListener('resize', resizeHelper.run);
    emitter.addListener('onChangeMnue', resizeHelper.run);
  }

  function renderChart() {
    chartInstance = echarts.getInstanceByDom(chartRef?.current) || echarts.init(chartRef?.current);
    chartInstance?.setOption(config, true);
    chartInstance.dispatchAction({
      type: 'showTip',
      seriesIndex: 0,
      dataIndex: 0,
    });
    chartInstance?.resize();
  }

  return <div ref={chartRef} style={{ width: '100%', height: '98%' }} />;
}

export default Charts;
